package edu.sdbi.judge.service.impl;

import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.vo.JsonResult;
import edu.sdbi.judge.domain.vo.StudentResult;
import edu.sdbi.judge.mapper.CommentMapper;
import edu.sdbi.judge.service.GetJudgeIpResultService;
import edu.sdbi.judge.util.ErrorUtil;
import edu.sdbi.judge.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Order(12)
@Service
public class Judge_12 implements GetJudgeIpResultService {
    @Autowired
    private HttpUtil httpUtil;

    @Value("${test.newsId:1}")
    private String newsID;

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public StudentResult getJudgeIpResult(String ip) {
        StudentResult studentResult = new StudentResult();
        studentResult.setItemNumber("12");

        try {
            // 直接使用配置中的newsID，无需数据库查询
            String url = "http://" + ip + "/statistics/comment";

            // 封装请求参数，使用配置中的newsID
            Map<String, String> params = new HashMap<>();
            params.put("newsId", newsID);
            params.put("newId", newsID);

            // 发送HTTP请求
            String resultStr = httpUtil.doGet(url, null, params);
            studentResult.setResult(resultStr);

            // 验证返回结果
            JsonResult jsonResult = JSONObject.parseObject(resultStr, JsonResult.class);
            if (jsonResult.getCode() == 200) {
                // 验证返回的数据结构和内容
                if (validateCommentData(jsonResult.getData(), newsID)) {
                    studentResult.setScore(2.0);
                    studentResult.setComment("测试通过：返回正确的评论量数据");
                } else {
                    studentResult.setScore(0.0);
                    studentResult.setComment("返回的数据格式或内容不符合要求");
                }
            } else {
                studentResult.setScore(0.0);
                studentResult.setComment("接口返回错误码：" + jsonResult.getCode() + "，错误信息：" + jsonResult.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            studentResult.setScore(0.0);
            studentResult.setResult(ErrorUtil.stackTraceToString(e));
            studentResult.setComment("执行测试时发生异常：" + e.getMessage());
        }
        return studentResult;
    }

    /**
     * 验证返回的评论量数据
     */
    private boolean validateCommentData(Object data, String newsId) {
        // 检查data是否为整数类型
        if (!(data instanceof Integer)) {
            return false;
        }

        int actualComments = (Integer) data;

        int count = commentMapper.countCommentsByNewsId(newsId);

        return count == actualComments;
    }
}
